<template>
  <van-form @submit="onSubmit" @failed="onFailed">
    <van-field
      v-model="form.phone"
      name="phone"
      clearable
      left-icon="phone-o"
      label="手机号"
      placeholder="手机号"
      :rules="[{ required: true, message: '请填写手机号' }]"
    />
    <van-field
      v-model="form.password"
      :type="type"
      name="password"
      clearable
      left-icon="warn-o"
      label="密码"
      placeholder="密码"
      :rules="[
        { required: true, message: '请填写密码' },
        { pattern: reg.pwd, message: '请输入正确的格式(6-8)' },
      ]"
      :right-icon="type != 'password' ? 'eye-o' : 'closed-eye'"
      @click-right-icon="changeType"
    />
    <div style="margin: 16px 0" class="links">
      <router-link :to="{ name: 'register' }" class="aitem color1"
        >没有账号,请注册</router-link
      >
      <router-link :to="{ name: 'forgetpwd' }" class="aitem color2"
        >找回密码</router-link
      >
    </div>
    <div style="margin: 16px 0">
      <van-button block type="info" native-type="submit">登录</van-button>
      <van-button class="mt20" block type="danger" native-type="reset"
        >重置</van-button
      >
    </div>
  </van-form>
</template>

<script>
export default {
  data() {
    return {
      form: {},
      type: "password",
    };
  },
  methods: {
    async onSubmit(value) {
    //   console.log(value);
      let res = await this.$ajax.findUser(value);
    //   console.log(res);
      if (res.length > 0) {
        this.ShowSuccess("登陆成功");
        localStorage.setItem("phone", value.phone);
        this.$router.push({ name: "mine" });
        this.changeUserInfo(res[0]); //存储全局的用户信息
      } 
      else {
        this.ShowFailMsg("用户名或密码错误");
      }
    },
    onFailed() {
      this.ShowFailMsg("请输入有效的登录信息");
    },
    changeType() {
      this.type = this.type == "password" ? "text" : "password";
    },
  },
  mounted() {
    // 判断是否存储了phone
    if (this.$route.query.phone) {
      this.form = { ...this.form, phone: this.$route.query.phone };
    //   console.log(1);
    } else {
      this.form = { ...this.form, phone: localStorage.getItem("phone") };
    //   console.log(2);
    }
  },
};
</script>

<style lang="scss" scoped>
</style>